from fastapi import APIRouter, Depends, Path, HTTPException, UploadFile, File, Request
from typing import List

from starlette.responses import JSONResponse

from service.sysUserService import SysUserService
from service.sysMenuService import SysMenuService
from schema.sysUserSchema import UserCreate, UserUpdate, UserDelete, PageParams, UserChange, UserProfile, UserPassword, \
    UserRole
from utils.response import ResponseUtil, ResponseModel
from urllib.parse import quote

from fastapi.responses import StreamingResponse
from datetime import datetime
from io import BytesIO

router = APIRouter(prefix="/sysUser", tags=["系统用户管理"])
user_service = SysUserService()
menu_service = SysMenuService()


@router.post(
    "",
    response_model=ResponseModel,
    summary="创建用户",
    description="创建一个新的系统用户，用户名不能重复。默认创建后状态为正常状态。",
    response_description="返回创建成功的用户信息"
)
async def create_user(user: UserCreate, request: Request):
    """创建新用户"""
    current_user = request.state.user
    creator = current_user["username"]
    result = await user_service.create_user(user, creator)
    return ResponseUtil.success(data=result, msg="创建用户成功")


@router.get(
    "/get/{user_id}",
    response_model=ResponseModel,
    summary="获取用户详情",
    description="根据用户ID获取用户的详细信息",
    response_description="返回用户的详细信息，包括基本信息、状态、创建时间等"
)
async def get_user_detail(user_id: int):
    """获取用户详情"""
    result = await user_service.get_user_by_id(user_id)
    return ResponseUtil.success(data=result)


@router.patch(
    "/update/{user_id}",
    response_model=ResponseModel,
    summary="更新用户",
    description="更新指定ID的用户信息。如果更新用户名，会检查是否与其他用户重复。支持部分字段更新。",
    response_description="返回更新后的用户信息"
)
async def update_user(user_id: int, user: UserUpdate, request: Request):
    """更新用户"""
    current_user = request.state.user
    updater = current_user["username"]
    result = await user_service.update_user(user_id, user, updater)
    return ResponseUtil.success(data=result, msg="更新用户成功")


@router.delete(
    "/batch/{user_ids}",
    response_model=ResponseModel,
    summary="批量删除用户",
    description="根据用户ID删除用户，支持多个ID(用逗号分隔)。此操作不可恢复，请谨慎操作。",
    response_description="返回成功删除的用户数量"
)
async def delete_users(request: Request, user_ids: str = Path(..., description="用户ID，多个用逗号分隔，如：1,2,3")):
    """批量删除用户"""
    # 将逗号分隔的字符串转换为整数列表
    try:
        id_list = [int(user_id.strip()) for user_id in user_ids.split(",")]
    except ValueError:
        raise ResponseUtil.error(code=400, msg="无效的用户ID格式")

    current_user = request.state.user
    updater = current_user["username"]
    count = await user_service.delete_users(id_list, updater)
    return ResponseUtil.success(data={"count": count}, msg=f"成功删除{count}个用户")


@router.get(
    "/page",
    response_model=ResponseModel,
    summary="分页查询用户列表",
    description="""
    分页获取用户列表，支持多条件查询：
    - 可按用户名模糊搜索
    - 可按手机号模糊搜索
    - 可按状态筛选
    - 可按使用标志筛选
    - 支持分页和排序
    默认按创建时间倒序排列
    """,
    response_description="返回分页数据，包含用户列表、总数、页码、每页大小"
)
async def get_user_list(
        params: PageParams = Depends()
):
    """分页获取用户列表"""
    users, total = await user_service.get_user_page(params)
    return ResponseUtil.success(data={
        "records": users,
        "total": total,
        "page": params.page_num,
        "limit": params.page_size
    })


@router.get(
    "/export",
    summary="导出用户数据",
    description="导出所有用户数据到Excel文件",
    response_description="返回Excel文件"
)
async def export_users():
    """导出用户数据到Excel"""
    excel_data = await user_service.export_users_excel()

    # 生成文件名
    filename = f"用户数据_{datetime.now().strftime('%Y%m%d%H%M%S')}.xlsx"
    # 对文件名进行 URL 编码，同时支持 UTF-8
    encoded_filename = quote(filename)

    headers = {
        'Content-Disposition': f'attachment; filename="{encoded_filename}"; filename*=utf-8\'\'{encoded_filename}',
        'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    }

    return StreamingResponse(
        BytesIO(excel_data.getvalue()),
        headers=headers,
        media_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    )


@router.get(
    "/importTemplate",
    summary="下载用户导入模板",
    description="下载用户导入的Excel模板文件",
    response_description="返回Excel模板文件"
)
async def get_import_template():
    """获取用户导入模板"""
    template_data = user_service.get_import_template()
    # 生成文件名
    filename = f"用户导入模板_{datetime.now().strftime('%Y%m%d%H%M%S')}.xlsx"
    encoded_filename = quote(filename)

    headers = {
        'Content-Disposition': f'attachment; filename="{encoded_filename}"; filename*=utf-8\'\'{encoded_filename}',
        'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    }

    return StreamingResponse(
        BytesIO(template_data.getvalue()),
        headers=headers,
        media_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    )


@router.post(
    "/import",
    response_model=ResponseModel,
    summary="导入用户数据",
    description="通过Excel文件批量导入用户数据",
    response_description="返回导入结果，包括成功数量和错误信息"
)
async def import_users(
        file: UploadFile = File(..., description="Excel文件")
):
    """导入用户数据"""
    # 验证文件类型
    if not file.filename.endswith(('.xls', '.xlsx')):
        return ResponseUtil.error(msg="只支持Excel文件格式（.xls, .xlsx）")

    # TODO: 获取当前登录用户信息作为creator
    creator = "admin"

    try:
        success_count, error_msgs = await user_service.import_users(file, creator)

        return ResponseUtil.success(data={
            "successCount": success_count,
            "errorMsgs": error_msgs
        }, msg=f"成功导入{success_count}条数据")

    except HTTPException as e:
        return ResponseUtil.error(msg=str(e.detail))
    except Exception as e:
        return ResponseUtil.error(msg=f"导入失败: {str(e)}")


@router.get(
    "/getRouters",
    response_model=ResponseModel,
    summary="获取用户菜单路由",
    description="获取当前登录用户的菜单路由树形结构数据",
    response_description="返回用户可访问的菜单路由树形结构"
)
async def get_user_routers(request: Request):
    """获取用户菜单路由"""
    current_user = request.state.user
    user_id = current_user.get("user_id")

    menu_tree = await menu_service.build_tree(user_id)
    return ResponseUtil.success(data=menu_tree)


@router.get(
    "/getInfo",
    response_model=ResponseModel,
    summary="获取用户信息",
    description="获取当前登录用户的详细数据",
    response_description="返回用户详细信息"
)
async def get_user_info(request: Request):
    """获取信息用户"""
    current_user = request.state.user
    user_id = current_user.get("user_id")

    result = await user_service.getInfo(user_id)
    return ResponseUtil.success(data=result)


@router.get(
    "/addInfo",
    response_model=ResponseModel,
    summary="获取用户新增信息",
    description="获取用户新增信息",
    response_description="返回新增用户所需信息"
)
async def get_user_add_info(request: Request):
    """获取用户新增信息"""
    current_user = request.state.user
    user_id = current_user.get("user_id")

    result = await user_service.get_add_info(user_id)
    return ResponseUtil.success(data=result)


@router.patch(
    "/changeStatus",
    response_model=ResponseModel,
    summary="更新用户状态",
    description="更新指定ID的用户状态",
    response_description="返回更新后的用户信息"
)
async def change_user_status(user: UserChange, request: Request):
    """更新用户状态"""
    current_user = request.state.user
    updater = current_user["username"]
    result = await user_service.change_status(user, updater)
    return ResponseUtil.success(data=result, msg="更新用户成功")


@router.get(
    "/profile",
    response_model=ResponseModel,
    summary="获取用户个人信息",
    description="获取用户个人信息",
    response_description="返回用户个人信息"
)
async def get_profile(request: Request):
    """获取用户个人信息"""
    current_user = request.state.user
    user_id = current_user.get("user_id")

    result = await user_service.get_profile(user_id)
    return ResponseUtil.success(data=result)


@router.patch(
    "/profile/update/{user_id}",
    response_model=ResponseModel,
    summary="更新用户状态",
    description="更新指定ID的用户状态",
    response_description="返回更新后的用户信息"
)
async def update_profile_user(user_id: int, user: UserProfile, request: Request):
    """更新用户状态"""
    current_user = request.state.user
    updater = current_user["username"]
    result = await user_service.update_profile_user(user_id, user, updater)
    return ResponseUtil.success(data=result, msg="更新用户成功")


@router.patch(
    "/updatePwd",
    response_model=ResponseModel,
    summary="更新密码",
    description="更新当前登录用户密码",
    response_description="返回更新后的用户信息"
)
async def update_password(user: UserPassword, request: Request):
    """更新密码"""
    current_user = request.state.user
    user_id = current_user["user_id"]
    updater = current_user["username"]
    result = await user_service.update_password(user_id, user, updater)
    return ResponseUtil.success(data=result, msg="更新用户成功")


@router.get(
    "/authRole/{user_id}",
    response_model=ResponseModel,
    summary="获取用户新增信息",
    description="获取用户新增信息",
    response_description="返回新增用户所需信息"
)
async def get_user_auth_role(request: Request, user_id: int):
    """获取用户新增信息"""
    current_user = request.state.user
    current_user_id = current_user.get("user_id")

    result = await user_service.get_auth_role_info(user_id, current_user_id)
    return ResponseUtil.success(data=result)


@router.patch(
    "/authRole",
    response_model=ResponseModel,
    summary="用户分配角色",
    description="用户分配角色",
    response_description="返回更新后的用户信息"
)
async def auth_roles(user_role: UserRole, request: Request):
    """用户分配角色"""
    current_user = request.state.user
    creator = current_user["username"]
    result = await user_service.batch_auth_roles(user_id=user_role.user_id, role_ids=user_role.role_ids, creator=creator)
    return ResponseUtil.success(data=result, msg="更新用户成功")
